﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace AIS.SharePoint.AspNetFBA.Code
{
    /// <summary>
    /// Contains common reused routines
    /// </summary>
    public class Common
    {

        /// <summary>
        /// Popup dialog aware application page close
        /// Closes the popup dialog if in a dialog, otherwise performs a javascript History.Back()
        /// </summary>
        public static void ClosePage()
        {
            ClosePage(null);
        }

        /// <summary>
        /// Popup dialog aware application page close
        /// </summary>
        /// <param name="redirectToLayoutsPage">Page to redirect to.  Must be relative to the /_layouts path.  If NullorEmpty, performs a History.Back() javascript command </param>
        public static void ClosePage(string redirectToLayoutsPage)
        {
            System.Web.HttpContext CurrentContext = System.Web.HttpContext.Current;
            bool IsDialog = IsCurrentContextADialog();
            if (IsDialog)
            {
                CurrentContext.Response.Clear();
                CurrentContext.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");
                CurrentContext.Response.Flush();
                CurrentContext.Response.End();
            }
            else if (!string.IsNullOrEmpty(redirectToLayoutsPage))
            {
                Microsoft.SharePoint.Utilities.SPUtility.Redirect(redirectToLayoutsPage, Microsoft.SharePoint.Utilities.SPRedirectFlags.RelativeToLayoutsPage, CurrentContext);
            }
            else
            {
                CurrentContext.Response.Clear();
                CurrentContext.Response.Write("<script type='text/javascript'>history.back();</script>");
                CurrentContext.Response.Flush();
                CurrentContext.Response.End();
            }
        }

        /// <summary>
        /// Returns a SharePoint localized resource string
        /// </summary>
        /// <param name="resourceKey">Resource key.  Required format: "$Resources:[key]"</param>
        /// <returns></returns>
        public static string GetLocalizedResource(string resourceKey)
        {
            string ReturnValue = "";
            try
            {
                ReturnValue = SPUtility.GetLocalizedString(resourceKey, "AIS.SharePoint.AspNetFBA", Microsoft.SharePoint.SPContext.Current.Web.Language);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                ReturnValue = "$ResError";
            }
            return ReturnValue;
        }

        /// <summary>
        /// Checks the current page context to determine if the page is displayed as a dialog / popup
        /// </summary>
        /// <returns>True for dialogs and popups</returns>
        public static bool IsCurrentContextADialog()
        {
            bool IsDialog = false;
            System.Web.HttpContext CurrentContext = System.Web.HttpContext.Current;
            if (CurrentContext != null)
            {
                string DialogValue = CurrentContext.Request.QueryString["IsDlg"];
                if (!string.IsNullOrEmpty(DialogValue))
                {
                    IsDialog = (DialogValue.Substring(0, 1) != "0");
                }
            }
            return IsDialog;
        }

        /// <summary>
        /// Processes an email
        /// </summary>
        /// <param name="toEMail">Send to e-mail address</param>
        /// <param name="subject">Subject line text</param>
        /// <param name="body">Body text</param>
        /// <param name="userName">User name.  Replaces %$username%</param>
        /// <param name="fullName">Full name.  Replaces %$fullname%</param>
        /// <param name="password">Password.  Replaces %$password%</param>
        /// <param name="siteUrl">SirURL.  Replaces %$siteurl%$</param>
        public static void SendEMail(string toEMail, string subject, string body, string userName, string fullName, string password, string siteUrl)
        {
                try
                {
                    StringBuilder EMailBody = new StringBuilder(body, body.Length * 2);
                    StringBuilder EMailSubject = new StringBuilder(subject, subject.Length * 2);

                    // Replace out variables
                    ReplaceVariables(EMailBody, EMailSubject, "%$fullname%", fullName);
                    ReplaceVariables(EMailBody, EMailSubject, "%$username%", userName);
                    ReplaceVariables(EMailBody, EMailSubject, "%$password%", password);
                    ReplaceVariables(EMailBody, EMailSubject, "%$siteurl%", siteUrl);

                    SPUtility.SendEmail(SPContext.Current.Web, true, false, toEMail, EMailSubject.ToString(), EMailBody.ToString());
                }
                catch (Exception ex)
                {
                    Code.Log.Error(ex, TraceSeverity.High, Code.Log.Category.CustomAction);
                }
        }

        private static void ReplaceVariables(StringBuilder body, StringBuilder subject, string key, string value)
        {
            body.Replace(key, value);
            subject.Replace(key, value);
        }

    }
}
